#include "../src/dulinklist.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* 声明底层链表的函数库 */
extern func_DLinkList fun_DLinkList;

typedef struct __value
{
    DLinkListNode node;
    int data;
} value_t;

int main(int argc, const char *argv[])
{
    int i; 

    value_t* pv = NULL;
    value_t v1, v2, v3, v4, v5, v6, v7, v8;

    v1.data = 1;
    v2.data = 2;
    v3.data = 3;
    v4.data = 4;
    v5.data = 5;
    v6.data = 6;
    v7.data = 7;
    v8.data = 8;


    DLinkList *dlist = fun_DLinkList.create();

    // 分别为头插入和尾插入，先简单的测试其中的一种，免得看数据乱

    fun_DLinkList.insert(dlist, (DLinkListNode *)&v1, fun_DLinkList.length(dlist));
    fun_DLinkList.insert(dlist, (DLinkListNode *)&v2, fun_DLinkList.length(dlist));
    fun_DLinkList.insert(dlist, (DLinkListNode *)&v3, fun_DLinkList.length(dlist));
    fun_DLinkList.insert(dlist, (DLinkListNode *)&v4, fun_DLinkList.length(dlist));
    fun_DLinkList.insert(dlist, (DLinkListNode *)&v5, fun_DLinkList.length(dlist));
    fun_DLinkList.insert(dlist, (DLinkListNode *)&v6, fun_DLinkList.length(dlist));
    fun_DLinkList.insert(dlist, (DLinkListNode *)&v7, fun_DLinkList.length(dlist));
    fun_DLinkList.insert(dlist, (DLinkListNode *)&v8, fun_DLinkList.length(dlist));


    // 复位游标开始后面的测试工作
    fun_DLinkList.reset(dlist);
    printf("\n链表中的数据 ：");
    for (i = 0; i < fun_DLinkList.length(dlist); i++)
    {
        pv = (value_t *)fun_DLinkList.get(dlist, i);
        printf("%d\t", pv->data);
    }
    printf("\n");

    

    /* 复位游标 */
    fun_DLinkList.reset(dlist);

    /* 开始进行约瑟夫的问题解决 */
    printf("Josephus's order is : ");
    while (fun_DLinkList.length(dlist) > 0)
    {
        value_t *temp = NULL;
        for(i = 1; i < 3; i++) fun_DLinkList.next(dlist);

        temp = (value_t *)fun_DLinkList.current(dlist);

        printf("%d  ", temp->data);
        fun_DLinkList.deleteNode(dlist, (DLinkListNode *)temp);
    }






    
    // 清空 + 销毁链表
    fun_DLinkList.clear(dlist);
    fun_DLinkList.destroy(&dlist);

    if(dlist == NULL) 
    {
        printf("\nfree success\n\n");
    }    
    else
    {
        free(dlist);
        printf("\nfree failed!\n\n");
    }
    
    return 0;
}

